//
//  SearchDirectoryViewController.m
//  HandyDialer
//
//	Developed by Team Synergy
//  Created by Jacky Li on 11/24/11.
//  Coders: Jacky Li and Jordan Tseng 
//  Graphic Designer: Derek Fong
//  Developer: Brad Lisson, Derek Fong, Jacky Li, Jeremy Gangoso, Jordan Tseng
//  Copyright HandyDialer 2011. All rights reserved.
//

#import "ContactResultViewController.h"

@implementation ContactResultViewController

@synthesize highlightArea;
@synthesize backgroundArea;
@synthesize contact1, contact2, contact3, contact4, pageDisplay;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark - View lifecycle


- (void)dealloc {
	[highlightArea release];
    [super dealloc];
}

- (void)viewDidLoad 
{
	DataStorage *data = [DataStorage sharedData];
	NSString *searchName = [data getSearchName];
	[self searchContact:searchName];
	[self refreshResultDisplay];
    counter = 0;
	defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
	// special case for white theme to make text readable
	if ([themeColor isEqual:@"white"])
	{
		contact1.textColor = [UIColor blackColor];
		contact2.textColor = [UIColor blackColor];
		contact3.textColor = [UIColor blackColor];
		contact4.textColor = [UIColor blackColor];
	}
	if (pageNum == 0)
	{
		[uniTimer invalidate];
		[highlightArea setImage:nil];
		[backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_notfound.png"]]];
	}
	else
	{
		[backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_results.png"]]];
	}
	[super viewDidLoad];
    
}

- (void)viewDidAppear:(BOOL)animated
{
	defaults = [NSUserDefaults standardUserDefaults];
    speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
	if (pageNum == 0)
	{
		[uniTimer invalidate];
		[highlightArea setImage:nil];
		[backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_notfound.png"]]];
	}
	else
	{
		if (uniTimer == nil)
			uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(optionChange) userInfo:nil repeats:YES];
		[super viewDidAppear:animated];
		[backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_results.png"]]];
	}
}

- (void)viewDidDisappear:(BOOL)animated
{
	[uniTimer invalidate];
	uniTimer = nil;
	[super viewDidDisappear:animated];
}

- (void)searchContact:(NSString *)keyword
{
	ABAddressBookRef tempBook = ABAddressBookCreate();
	// look for contact with keyword
	CFArrayRef unsortedResults = ABAddressBookCopyPeopleWithName(tempBook,(CFStringRef)keyword);
	if (unsortedResults != nil)
	{
		resultList = CFArrayCreateMutableCopy(kCFAllocatorDefault,CFArrayGetCount(unsortedResults),unsortedResults);
	
		//sort results based on first name
		CFArraySortValues(resultList,CFRangeMake(0,CFArrayGetCount(resultList)),(CFComparatorFunction) ABPersonComparePeopleByName,(void *) kABPersonSortByFirstName);
	
		// determines total number of pages for results
		if (CFArrayGetCount(resultList) % 4 == 0)
		{
			maxPages = CFArrayGetCount(resultList)/4;
		}
		else
		{
			maxPages = CFArrayGetCount(resultList)/4+1;
		}
		if (pageNum < maxPages)
		{
			pageNum = 1;
		}
	}
	else
	{
		pageNum = 0;
		maxPages = 0;
	}
}

- (NSString *)getContactName:(int)entry
{
	NSString *fullName = (NSString *)ABRecordCopyCompositeName(CFArrayGetValueAtIndex(resultList, entry));
	NSLog(@"%@",fullName);
	return fullName;
}


// lists the 4 results based on current page number
- (void)refreshResultDisplay
{
	if (pageNum > 0)
	{

		if (0+(pageNum-1)*4 < CFArrayGetCount(resultList))
		{
			contact1.text = [self getContactName:(0+(pageNum-1)*4)];
		}
		else
		{
			contact1.text = nil;
		}
	
		if (1+(pageNum-1)*4 < CFArrayGetCount(resultList))
		{
			contact2.text = [self getContactName:(1+(pageNum-1)*4)];
		}
		else
		{
			contact2.text = nil;
		}
	
		if (2+(pageNum-1)*4 < CFArrayGetCount(resultList))
		{
			contact3.text = [self getContactName:(2+(pageNum-1)*4)];
		}
		else
		{
			contact3.text = nil;
		}
		if (3+(pageNum-1)*4 < CFArrayGetCount(resultList))
		{
			contact4.text = [self getContactName:(3+(pageNum-1)*4)];
		}
		else
		{
			contact4.text = nil;
		}
	}
	pageDisplay.text = [NSString stringWithFormat: @"Page %d of %d", pageNum, maxPages];
}

// strips () and space from number for consistency and dialing purposes
- (NSString *)stripNumber:(NSString *)rawNumber
{
	if ([rawNumber length] > 1)
	{
		if ([rawNumber characterAtIndex:0] == '1' && [rawNumber characterAtIndex:1] == ' ')
		{
			rawNumber = [rawNumber substringFromIndex:3];
			rawNumber = [NSString stringWithFormat:@"1-%@-%@",[rawNumber substringToIndex:3],[rawNumber substringFromIndex:5]];
			NSLog(@"%@",rawNumber);
			
		}
		else if ([rawNumber characterAtIndex:0] == '(')
		{
			rawNumber = [rawNumber substringFromIndex:1];
			rawNumber = [NSString stringWithFormat:@"%@-%@",[rawNumber substringToIndex:3],[rawNumber substringFromIndex:5]];
		}
		return rawNumber;
	}
	else
	{
		return rawNumber;
	}
}

- (void)returnToView:(NSString *)viewName:(UIViewController *)previousView
{
	// recursively find view to return to
	previousView = [previousView presentingViewController];
	NSLog(@"%@", previousView.nibName);
	if (previousView.nibName == viewName)
	{
		[previousView dismissModalViewControllerAnimated:NO];
	}
	else
	{
		[self returnToView:(viewName):(previousView)];
	}
}

- (IBAction)switchView:(id)sender{
	if (pageNum > 0)
	{
		switch (counter)
		{
				// goto first page
			case 1:
			{
				if (pageNum > 1)
				{
					counter = 0;
					pageNum = 1;
					[self refreshResultDisplay];
					//insert refresh function
				}
				break;
			}
				// previous page
			case 2:
			{
			
				if (pageNum > 1)
				{
					counter = 0;
					pageNum--;
					[self refreshResultDisplay];

				}
				break;
			}
				// next page
			case 3:
			{
			
				if (pageNum < maxPages)
				{
					counter = 0;
					pageNum++;
					[self refreshResultDisplay];
					//insert refresh function
				}
				break;
			}
				// last page
			case 4:
			{
				if (pageNum < maxPages)
				{
					counter = 0;
					pageNum = maxPages;
					[self refreshResultDisplay];

				}
				break;
			}
			// first entry
			case 5:
			{
				if (contact1.text != nil)
				{
					counter = 0;
					DataStorage *data = [DataStorage sharedData];
					[data setCurrentContact:CFArrayGetValueAtIndex(resultList, (0+(pageNum-1)*4))];
					ContactCardViewController *myViewController = [[ContactCardViewController alloc]
															initWithNibName:@"ContactCardView"
															  bundle:nil];
					[self presentModalViewController:myViewController animated:NO];

				}
				break;
			}
				// second entry
			case 6:
			{
				if (contact2.text != nil)
				{
					counter = 0;
					DataStorage *data = [DataStorage sharedData];
					[data setCurrentContact:CFArrayGetValueAtIndex(resultList, (1+(pageNum-1)*4))];
					ContactCardViewController *myViewController = [[ContactCardViewController alloc]
															   initWithNibName:@"ContactCardView"
															   bundle:nil];
					[self presentModalViewController:myViewController animated:NO];
				
				}
				break;
			}
				// third entry
			case 7:
			{
				if (contact3.text != nil)
				{
					counter = 0;
					DataStorage *data = [DataStorage sharedData];
					[data setCurrentContact:CFArrayGetValueAtIndex(resultList, (2+(pageNum-1)*4))];
					ContactCardViewController *myViewController = [[ContactCardViewController alloc]
															   initWithNibName:@"ContactCardView"
															   bundle:nil];
					[self presentModalViewController:myViewController animated:NO];
				}
				break;
			}
			// fourth entry
			case 8:
			{
				if (contact4.text != nil)
				{
					counter = 0;
					DataStorage *data = [DataStorage sharedData];
					[data setCurrentContact:CFArrayGetValueAtIndex(resultList, (3+(pageNum-1)*4))];
					ContactCardViewController *myViewController = [[ContactCardViewController alloc]
															   initWithNibName:@"ContactCardView"
															   bundle:nil];
					[self presentModalViewController:myViewController animated:NO];
				
				}
				break;
			}
			// return to contact menu
			case 9:
			{
				counter = 0;
				[self returnToView:@"ContactView":self];

			}
		}
	}
	else
	{
		[self returnToView:@"ContactView":self];
	}
}

- (void)highlightChange:(NSString *)picture
{
    UIImage *image = [UIImage imageNamed: picture];
    [highlightArea setImage:image];
	
}

// Decides which screen to go to
-(void)optionChange 
{
    if (counter == 9)
    {
        counter = 0;
    }
    counter += 1;
    NSString *next = highlightColor;
	next = [next stringByAppendingString:@"_contacts_results_"];  
	next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", counter]];
	next = [next stringByAppendingString:@".png"];
	[self highlightChange:next];
}

@end
